package com.inspur.xiaoju.controller;

import com.inspur.xiaoju.common.ApiResponse;
import com.inspur.xiaoju.dto.CreateWorkspaceDto;
import com.inspur.xiaoju.model.Workspace;
import com.inspur.xiaoju.service.WorkspaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;  // 添加这个导入
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/workspaces")
public class WorkspaceController {

    @Autowired
    private WorkspaceService workspaceService;
    
    @PostMapping
    public ApiResponse<Map<String, String>> create(@Valid @RequestBody CreateWorkspaceDto createDto,
                                                  @RequestAttribute("userId") String userId,
                                                  @RequestAttribute("username") String username) {
        Workspace workspace = workspaceService.create(createDto, userId, username);
        // 替换 Map.of() 为 HashMap
        Map<String, String> result = new HashMap<>();
        result.put("id", workspace.getId());
        return ApiResponse.success(result);
    }
    
    @GetMapping("/{id}")
    public ApiResponse<Workspace> findById(@PathVariable String id) {
        return ApiResponse.success(workspaceService.findById(id));
    }
    
    @GetMapping("/user")
    public ApiResponse<List<Workspace>> findByCreatorId(@RequestAttribute("userId") String userId) {
        return ApiResponse.success(workspaceService.findByCreatorId(userId));
    }
    
    @PutMapping("/{id}")
    public ApiResponse<Workspace> update(@PathVariable String id, @RequestBody Map<String, Object> updates) {
        return ApiResponse.success(workspaceService.update(id, updates));
    }
    
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable String id) {
        workspaceService.delete(id);
        return ApiResponse.success(null);
    }
}